<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\User;
use app\model\Role;
use app\model\Menu;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        $response = $next($request);
        //return $response;
        $ctlr = $request->controller();
        $act = $request->action();
        $href = strtolower(join('/', [$ctlr, $act]));
        
        $white_controller = config('auth.white_controller_list');
        $arr_except = config('auth.white_list');
        if (in_array(strtolower($ctlr), $white_controller) || in_array($href, $arr_except)) {
            return $response;
        }
        
        $role_id = session('info.role_id');
        if($role_id ==1){
            return $response;
        }
        if (empty($role_id)) {
            return redirect('/no_permission');
        // 权限判定
        } else {
            $r = Role::cache(true)->find($role_id);
            $menus = Menu::cache(true)->field('id, href, title')->select();
            $menu_id = 0;
            foreach ($menus as $menu) {
                if (strtolower($menu->href) == $href) {
                    $menu_id = $menu->id;
                }
            }
            
            
            if (!in_array($menu_id, $r->rules)) {
                trace($menu_id);
                trace($r->rules);
                if(request()->isAjax()){
                    //return json(['code'=>4,'msg'=>'您没有操作权限，请联系主管或管理员']);
                    return $response;
                }
                return redirect('/no_permission');
                
            }
        }
        
        return $response;
    }

}